package com.sh.caryr.erp.exception.handler;

import com.sh.caryr.erp.entity.ResultMessage;
import com.sh.caryr.erp.exception.ResultCode;
import com.sh.caryr.erp.exception.RestServiceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RestServiceException.class)
    @ResponseBody
    public ResponseEntity<ResultMessage> restServiceExceptionHandler(RestServiceException exception) {
        HttpStatus httpStatus = exception.getHttpStatus() != null ? exception.getHttpStatus() : HttpStatus.BAD_REQUEST;
        exception.printStackTrace();
        return new ResponseEntity<>(exception.getResultMessage(), httpStatus);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResultMessage<RuntimeException> unKnowExceptionHandler(RuntimeException ex) {
        ex.printStackTrace();
        ResultMessage<RuntimeException> resultMessage = new ResultMessage<>(ex);
        resultMessage.setMsgCode(ResultCode.UNKNOWN);
        return resultMessage;
    }
}
